package hd

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"time"
)

type ResPTokenContext struct {
	AccessToken    string    `json:"access_token"`
	TokenType      string    `json:"token_type"`
	ExpiresIn      int64     `json:"expires_in"`
	Scope          string    `json:"scope"`
	IsHdOem        bool      `json:"isHdOem"`
	ValidStartTime time.Time `json:"validStartTime"`
	ValidEndTime   time.Time `json:"validEndTime"`
	CreateTime     time.Time `json:"createTime"`
	CompanyName    string    `json:"companyName"`
	Type           int       `json:"type"`
	Authorities    []string  `json:"authorities"`
	Acct           string    `json:"acct"`
	Email          string    `json:"email"`
	ClientId       string    `json:"client_id"`
	Jti            string    `json:"jti"`
}

func GetBasicAuth(clientId, clientSecret string) string {
	clientContent := clientId + ":" + clientSecret
	return "Basic " + base64.StdEncoding.EncodeToString([]byte(clientContent))
}

// GetAccessToken 获取请求数据的token
func GetAccessToken() (ResPTokenContext, error) {
	client := &http.Client{}
	req, _ := http.NewRequest("POST", AuthUrl+"/oauth/partner/token?auth_type=partner_client_credential", nil)
	req.Header.Add("Authorization", GetBasicAuth(ClientId, ClientSecret))
	resp, _ := client.Do(req)
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			fmt.Println("close err")
		}
	}(resp.Body)
	body, _ := ioutil.ReadAll(resp.Body)
	//fmt.Println("原返回："+string(body))
	var token = ResPTokenContext{}
	err := json.Unmarshal(body, &token)
	if err != nil {
		return token, err
	}
	return token, nil
}
